package org.carl.component.dingtalk.robot.service.impl;

import cn.hutool.core.util.StrUtil;
import org.carl.component.dingtalk.robot.annotation.EnableDingTalkRobot;
import org.carl.component.dingtalk.robot.bean.DingTalkRobot;
import org.carl.component.dingtalk.robot.bean.DingTalkRobotVo;
import org.carl.component.dingtalk.robot.model.DingTalkResult;
import org.carl.component.dingtalk.robot.model.MsgModel;
import org.carl.component.dingtalk.robot.service.DingTalkService;
import org.carl.component.dingtalk.robot.util.DingTalkRebootUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@ConditionalOnBean(annotation = EnableDingTalkRobot.class)
public class DingTalkServiceImpl implements DingTalkService {

    /**
     * 机器人列表数据
     */
    @Autowired
    private DingTalkRobot dingTalkRobot;

    @Override
    public DingTalkResult sendReboot(String webhook, String secret, MsgModel msgModel) throws Exception {
        return DingTalkRebootUtil.sendReboot(webhook, secret, msgModel.toString());
    }

    @Override
    public DingTalkResult sendReboot(DingTalkRobotVo robot, MsgModel msgModel) throws Exception {
        return sendReboot(robot.getWebhook(),robot.getSecret(),msgModel);
    }

    @Override
    public DingTalkResult sendReboot(String robotId, MsgModel msgModel) throws Exception {
        DingTalkRobotVo robot=getRobot(robotId);
        return sendReboot(robot, msgModel);
    }

    /**
     * 获取机器人数据信息
     *
     * @param robotId String 机器人id
     * @return DingTalkRobotVo
     */
    @Override
    public DingTalkRobotVo getRobot(String robotId) {
        List<DingTalkRobotVo> robot = dingTalkRobot.getRobot();
        if (null != robot && robot.size() > 0) {
            return robot.stream().filter(r -> StrUtil.equals(r.getId(), robotId)).findFirst().orElse(null);
        }
        return null;
    }
}
